import os
import re
import argparse
from pathlib import Path
from shutil import copy2

def copy_template_files(data_dir, dest_path):
    # Copy all files from data directory to destination root
    for file in data_dir.iterdir():
        if file.is_file():
            # Check if file already exists in destination
            if (dest_path / file.name).exists():
                print(f"File already exists, skipping: {dest_path / file.name}")
                continue
            dest_file = dest_path / file.name
            try:
                copy2(file, dest_file)
                print(f"Copied template file to root: {dest_file}")
            except:
                print(f"fail to copy: {file}")


def create_project_structure(markdown_content, dest_dir):
    # Convert dest_dir to Path object for better path handling
    dest_path = Path(dest_dir)
    # Get the data directory path
    data_dir = Path(__file__).parent / "data"
    
    # Split content into lines and remove empty lines
    lines = [line.strip() for line in markdown_content.split('\n') if line.strip()]
    
    # Track current path and hierarchy level
    current_path = [dest_path]
    
    state_level = 0
    for line in lines:
        # Skip lines that are not headers or files
        if not line.startswith('#') and '.' not in line:
            continue
            
        if line.startswith('#'):
            # Count the level of header
            current_level = len(re.match('^#+', line).group())
            # Get folder name by removing '#' and spaces
            folder_name = line.lstrip('#').strip()
            
            # Adjust current path based on header level
            if current_level > state_level:
                state_level = current_level
                # breakpoint()
            else:
                current_path = current_path[:current_level]
                state_level = current_level
                
            current_path.append(folder_name)
           
            assert len(current_path) > 0,  f"{current_path}, 目录层级发生错误"
            
            # Create folder
            folder_path = Path(*current_path)
            folder_path.mkdir(parents=True, exist_ok=True)
            print(f"Created directory: {folder_path}")
            
        # Handle files
        elif '.' in line:
            file_name = line.strip()
            file_path = Path(*current_path) / file_name
            source_file = data_dir / file_name
            
            if source_file.exists():
                # If file exists in data directory, copy it
                copy2(source_file, file_path)
                print(f"Copied file from template: {file_path}")
            else:
                # Create empty file if no template exists
                file_path.touch(exist_ok=True)
                print(f"Created empty file: {file_path}")

def generate_markdown_structure(path, level=0):
    """Generate markdown content from directory structure."""
    content = []
    path = Path(path)
    
    # Skip hidden files and directories
    if path.name.startswith('.'):
        return content
        
    # Add current directory as header if not root level
    if level > 0:
        content.append('#' * level + ' ' + path.name)
    
    # List all files first
    for item in sorted(path.iterdir()):
        if item.is_file() and not item.name.startswith('.'):
            content.append(item.name)
    
    # Then process subdirectories
    for item in sorted(path.iterdir()):
        if item.is_dir() and not item.name.startswith('.'):
            content.extend(generate_markdown_structure(item, level + 1))
    
    return content

def main():
    # Get the directory where the script is located
    script_dir = Path(__file__).parent

    # Set up argument parser
    parser = argparse.ArgumentParser(description='Create project structure from markdown file')
    parser.add_argument(
        '-d', '--directory',
        default=os.getcwd(),
        help='Destination directory for the project structure (default: current directory)'
    )
    parser.add_argument(
        '-m', '--markdown',
        default=None,
        help='Path to the markdown file (default: <project_root>/data/project_structure.md)'
    )
    parser.add_argument(
        '--update-markdown',
        action='store_true',
        help='Update the markdown file with current directory structure'
    )
    
    args = parser.parse_args()
    dest_path = Path(args.directory)
    
    try:
        data_dir = Path(__file__).parent / "data"
        copy_template_files(data_dir, dest_path)

        markdown_file_for_project_structure = args.markdown
        if not markdown_file_for_project_structure:
            markdown_file_for_project_structure = dest_path / 'project_structure.md'
        
        if args.update_markdown:
            # Generate new markdown content from current directory structure
            structure = generate_markdown_structure(dest_path)
            markdown_content = '\n'.join(structure)
            
            # Write the updated content to the markdown file
            with open(markdown_file_for_project_structure, 'w', encoding='utf-8') as f:
                f.write(markdown_content)
            print(f"\nUpdated project structure markdown file: {markdown_file_for_project_structure}")
        else:
            # Read markdown content from file
            with open(markdown_file_for_project_structure, 'r', encoding='utf-8') as f:
                markdown_content = f.read()
            
            # Create project structure with destination directory
            create_project_structure(markdown_content, args.directory)
            print(f"\nProject structure created successfully in: {args.directory}")
        
    except FileNotFoundError:
        print(f"Error: Could not find file {args.markdown}")
    except Exception as e:
        print(f"Error: {str(e)}")

if __name__ == "__main__":
    main()
